import time,sys
import machine
import network
import ujson as json
import urequests as requests
from util import display,welcome
from window import Window
from questionWindow import Button

welcome('Robot3c   V0.1')

##########################
class MainWindow(Window):
	def __init__(self,title="WeatherQuery"):
		Window.__init__(self)
		self.title = title

		self.btn_query = Button("Query",50,40,40,12)
		self.btn_query.cb_hold = self.query_city_list
		Window.add(self,self.btn_query)

		Window.setDrawCB(self,self.cb_draw)

	def run(self):
		Window.run(self)

	def cb_timeout(self):
		print("idle timeout")

	def cb_draw(self):
		display.text(self.title,2,2,1)
		
	def query_city_list(self):
		gc.collect()
		print("1.Free mem: ",gc.mem_free())
		sta_if = network.WLAN(network.STA_IF)
		sta_if.active(False)
		if not sta_if.isconnected():
			print('connecting to network...')
			sta_if.active(True)
			sta_if.connect("JC-0877ab","12345678")
			while not sta_if.isconnected():
				pass
		print('network config:', sta_if.ifconfig())
		if sta_if.isconnected():
			display.fill(0)
			display.text("Getting Citys...", 0, 20)
			display.show()
		else:
			display.fill(0)
			display.text("No network!", 0, 20)
			display.show()
			time.sleep(2)
			return
		
		city_list=None
		URL = 'http://192.168.4.1:8080/?query'
		r = requests.get(URL)
		if r.status_code == 200:
			r_trans = r.text.replace("'", '"')
			r_json = json.loads(r_trans)
			print(r_json["result"])
			city_list = r_json["result"]
			r.close()

		from cityWindow import CityWindow
		w = CityWindow(city_list)
		w.run()

		del(w)
		del(CityWindow)
		del(sys.modules['cityWindow'])
		gc.collect()
		print("2.Free mem: ",gc.mem_free())
		print()
##################################
print("Free mem: ",gc.mem_free())
print(sys.modules)

print("Hold or click.")

mw = MainWindow(title="Weather App")
mw.run()
del(mw)
gc.collect() # very import!!!
print("Free mem: ",gc.mem_free())

